package com.vgooo.client.vchannel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.AdvInfo;
import com.vgooo.bean.Brand;
import com.vgooo.bean.NewListInfo;
import com.vgooo.bean.VideoListInfo;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.ui.DiverAdapter;
import com.vgooo.client.ui.HorizontalListView;
import com.vgooo.client.ui.PullDownView;
import com.vgooo.client.ui.PullDownView.OnPullDownListener;
import com.vgooo.client.ui.PullToRefreshView;
import com.vgooo.client.ui.PullToRefreshView.OnFooterRefreshListener;
import com.vgooo.client.ui.PullToRefreshView.OnHeaderRefreshListener;
import com.vgooo.client.ui.PullToRefreshView4V;
import com.vgooo.client.ui.SortAdapter;
import com.vgooo.client.ui.VGListView;
import com.vgooo.client.vchannel.news.NewsAdapter;
import com.vgooo.util.BitmapUtils;
import com.vgooo.util.DataApi;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.JsonParserUtils;
import com.vgooo.util.ListViewUtils;

public class VChannelActivity extends VGActivity {

	private final static String className = "VChannelActivity";// 获取类名，用于调试
	private List<Brand> brands;// 品牌信息
	private SortAdapter brandAdapter;
	private HorizontalListView brandsList;// 品牌信息列表
	private View hasMore;
	// private LinearLayout brandsLayout ;
	// private List<TextView> tvs ;

	private int currentBartag = 0;// 现在选中标签的位置

	// private AdvView advView ;//广告信息
//	private ImageView advImage; // 广告图片
	private List<AdvInfo> advs;
	// private ViewPager viewPager;// 广告控件
	// private ViewAdapter viewAdapter;
	// private List<ImageView> points;// 广告小圆点
	// private LinearLayout pointsLayout;// 广告小圆点
	// private Looping looping;
	// private int currentAdv;// 正在显示的广告
	// private OnClickListener clickListener;

	// private LinearLayout seeMoreLayout; // 更多层
	// private TextView footerLoadingProgress; // 页脚加载中
	// private TextView footerLoadingMore; // 页脚更多
	private TextView footLoadingseeMore;// 加载更多
	private ProgressBar footLoadingProgressBar;// 进度条
	private View footView;// 底部加载更多

	private List<NewListInfo> news;// 视频信息列表
	// private PullToRefreshView pullToRefreshView;// 上拉显示更多，下拉更新控件
	private PullDownView mPullDownView;// 上拉显示更多，下拉更新控件
	private OnPullDownListener onPullDownListener;// 监听上拉显示更多，下拉更新控件
	// private PullDownView pullDownView;
	private ListView videsList;// 视频信息列表显示控件
	private NewsAdapter newsAdapter;// 视频信息列表适配器
	private int total;// 视频信息总数
	private int allPage;// 总页数
	private int per = 10;// 每页视频数量
	private int currentPage = 1;// 现在所在的页

	// private ListView diver;// 使界面一打开就显示顶部广告

	private Context context = this;

	private boolean isFirst = true;

	private boolean isRefresh = false;

	// private ScrollView scrollView ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		detailVeiw = inflater.inflate(R.layout.v_channel_main, null);
		setContentView(detailVeiw);
		initView();
		// setContentView(blank);
		needNewLoading = true;
		addListener();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
//		new DataSAsyncLoader(cparent).execute(null);
		init() ;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
		// looping.start(1500);
		// setContentView(detailVeiw);
		if(news==null||news.isEmpty()){
			init();
		}

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
		// looping.stop();
	}

	@Override
	public void initView() {
		// TODO Auto-generated method stub
		// viewPager = (ViewPager) findViewById(R.id.v_channel_album_view);
		//
		// pointsLayout = (LinearLayout)
		// findViewById(R.id.v_channel_album_point);

		// pullDownView = (PullDownView) findViewById(R.id.v_channel_ListView);
		// diver = (ListView) findViewById(R.id.v_channel_diver_listview);

		// scrollView = (ScrollView) findViewById(R.id.scroll);

		// pullToRefreshView = (PullToRefreshView)
		// findViewById(R.id.v_channel_pull_to_refresh_view);
		// pullToRefreshView.onHeaderRefreshComplete();
		// videsList = (VGListView) findViewById(R.id.v_channel_ListView);
		mPullDownView = (PullDownView) findViewById(R.id.v_channel_PullDownView);
		videsList = mPullDownView.getListView();
		// 诉它数据加载完毕;
		mPullDownView.notifyDidLoad();
//		advImage = (ImageView) inflater.inflate(R.layout.v_channel_image, null);
//		videsList.addHeaderView(advImage);

		brandsList = (HorizontalListView) findViewById(R.id.v_channel_brands);

		hasMore = findViewById(R.id.v_channel_brands_sort_more);

		footView = inflater.inflate(R.layout.listview_foot, null);
		footLoadingseeMore = (TextView) footView
				.findViewById(R.id.listview_foot_seee_more);
		footLoadingProgressBar = (ProgressBar) footView
				.findViewById(R.id.listview_foot_progressBar);
		footLoadingProgressBar.setVisibility(View.INVISIBLE);

		// looping = new Looping();

		// brandsLayout = (LinearLayout)
		// findViewById(R.id.v_channel_brands_layout);

		// advImage = (ImageView) findViewById(R.id.v_channel_album_view_image)
		// ;

		// footerLoadingProgress = (TextView)
		// findViewById(R.id.footer_loading_progress);
		// footerLoadingMore = (TextView)
		// findViewById(R.id.footer_loading_more);
		// seeMoreLayout = (LinearLayout) findViewById(R.id.see_more);

	}

	LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
			LayoutParams.FILL_PARENT);

	@Override
	public void setupView(){
		// TODO Auto-generated method stub

		

		DebugTools.log(className, "brands = " + brands);
		if (isFirst) {
			brandAdapter = new SortAdapter(brands, R.layout.bartags_item,
					R.id.brand_tv, hasMore, context);
			brandsList.setAdapter(brandAdapter);
			brandsList.setVisibility(View.VISIBLE);
			
//			BitmapUtils.loaderImage(advs.get(0).img, advImage, context);
			isFirst = false;
			videsList.addFooterView(footView);

		}

		newsAdapter = new NewsAdapter(news, this);
		videsList.setAdapter(newsAdapter);
		mPullDownView.enableAutoFetchMore(true, 1);
		// 诉它数据加载完毕;
		mPullDownView.notifyDidLoad();
		// 告诉它获取更多完毕

		currentPage++;

		footLoadingProgressBar.setVisibility(View.INVISIBLE);
		footLoadingseeMore.setText("查看更多");
		
		//清除软引用中图片缓存缓存
		if(newsAdapter.getCount()>30){
			BitmapUtils.cleanCache();
		}
	}

	@Override
	public void addListener() {
		// TODO Auto-generated method stub
		// 品牌列表监听器
		brandsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Brand brand = (Brand) brandAdapter.getItem(position);
//				new DataSAsyncLoader(cparent).execute(null);
				init() ;
				brandAdapter.tvs.get(currentBartag).setBackgroundResource(0);
				currentBartag = position;
				brandAdapter.tvs.get(currentBartag).setBackgroundResource(
						R.drawable.sort_text_select_bg);

			}
		});

		// 设置广告切换监听
		// viewPager.setOnPageChangeListener(new OnPageChangeListener() {
		//
		// @Override
		// public void onPageSelected(int position) {
		// // TODO Auto-generated method stub
		// currentAdv = position;
		// setPiontsBg(currentAdv);
		// }
		//
		// @Override
		// public void onPageScrolled(int arg0, float arg1, int arg2) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void onPageScrollStateChanged(int arg0) {
		// // TODO Auto-generated method stub
		//
		// }
		// });

		// 广告单击事件监听
		// clickListener = new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// HttpUtils.browser(advs.get(currentAdv).url, context);
		// }
		// };
		// // 视频列表监听事件
		videsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				NewListInfo newInfo = null ;
//				if(position == 0){
//					newInfo = (NewListInfo) newsAdapter
//							.getItem(position);
//				}else{
//					newInfo = (NewListInfo) newsAdapter
//							.getItem(position-1);
//				}
				newInfo = (NewListInfo) newsAdapter
						.getItem(position);
				if (newInfo.newsType.equals(NewListInfo.NEWS_TYPE_NEWS)) {
					Main.news_detailIntent.putExtra("id",
							Integer.parseInt(newInfo.news_id));
					ViewLayout.setViewPre(true, "新闻详情",
							ViewLayout.TAB_TAG_NEWS_DETAIL,cparent);
				} else if (newInfo.newsType.equals("album")) {

					Bundle bundle = new Bundle();
					bundle.putSerializable(NewListInfo.NEWS_TYPE_ALBUM, newInfo);
					Main.album_detailIntent.putExtra(
							NewListInfo.NEWS_TYPE_ALBUM, bundle);
					ViewLayout.setViewPre(true, "图赏详情",
							ViewLayout.TAB_TAG_ALBUM_DETAIL,cparent);
				} else if (newInfo.newsType.equals(NewListInfo.NEWS_TYPE_VIDEO)) {
					HttpUtils.browser(newInfo.v_source_url, context);
				} else {
					DebugTools.toast(context, "未知类型的新闻:" + newInfo.newsType);
				}
			}
		});

		onPullDownListener = new OnPullDownListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				currentPage = 1;
				isRefresh = true;
				new DownLaodData(context).execute("");
			}

			@Override
			public void onMore() {
				// TODO Auto-generated method stub
				footLoadingProgressBar.setVisibility(View.VISIBLE);
				footLoadingseeMore.setText("加载中..");
				isRefresh = false;
				new DownLaodData(context).execute("");
			}
		};
		mPullDownView.setOnPullDownListener(onPullDownListener);
		

	}

	@Override
	public void flashView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void getData()  {
		try {
			// TODO Auto-generated method stub
			String urlPath;
			String jsonString;

			// 获取品牌信息
			if (isFirst) {
				urlPath = HttpUtils.BASE_URI + "bartags?type=n";
				jsonString = HttpUtils.getJsonString(urlPath);
				List<Map<String, Object>> list = GSonTools
						.getMulObjectList(jsonString);
				brands = new ArrayList<Brand>();
				Brand b = new Brand();
				b.brand_id = "0";
				b.brand_name = "全部";
				brands.add(b);
				for (Map<String, Object> map : list) {
					Brand brand = new Brand();
					brand.brand_id = (String) map.get("bt_id");
					brand.brand_name = (String) map.get("bt_tag");
					brands.add(brand);
				}
			}

			// 获取广告信息
			// urlPath = HttpUtils.BASE_URI + "newsad" ;
			// getAdvInfos(urlPath);

			// 获取广告信息
			urlPath = HttpUtils.BASE_URI + DataApi.KEY_ADV;
			jsonString = HttpUtils.getJsonString(urlPath);// datas.get(DataApi.KEY_ADV);
			List<Map<String, Object>> mapAdvs = GSonTools
					.getMulObjectList(jsonString);
			advs = new ArrayList<AdvInfo>();
			for (Map<String, Object> map : mapAdvs) {
				AdvInfo adv = new AdvInfo();
				adv.img = (String) map.get("image");
				adv.url = (String) map.get("link");
				advs.add(adv);
			}

			// 获取视频信息
			urlPath = HttpUtils.BASE_URI + "getnews?page=1per=1";
			jsonString = HttpUtils.getJsonString(urlPath);
			Map<String, Object> infos = GSonTools.getObjectMaps(jsonString);
			currentPage = 1;
			news = getVideos(currentPage, per);
			total = Integer.parseInt((String) infos.get("total"));// 获取视频信息总条数
			initPage();// 初始化分页信息
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e) ;
		}

	}

	private void getAdvInfos(String urlPath) throws Exception {
		String jsonString = HttpUtils.getJsonString(urlPath);

		List<Map<String, Object>> mapAdvs = GSonTools
				.getMulObjectList(jsonString);
		advs = new ArrayList<AdvInfo>();
		for (Map<String, Object> map : mapAdvs) {
			AdvInfo adv = new AdvInfo();
			adv.img = (String) map.get("img");
			adv.url = (String) map.get("url");
			adv.img_small = (String) map.get("img_small");

			advs.add(adv);
		}
		// log(advs.toString());
	}

	/**
	 * 获取指定分页视频信息
	 * 
	 * @param page
	 * @param per
	 * @return
	 * @throws IOException
	 */
	public List<NewListInfo> getVideos(int currentPage, int per)
			throws Exception {
		int btid = Integer.parseInt(brands.get(currentBartag).brand_id);
		ArrayList<NewListInfo> videos = null;
		String urlPath = HttpUtils.BASE_URI + "getnews?page=" + currentPage
				+ "&per=" + per + "&btid=" + btid;
		String jsonString = HttpUtils.getJsonString(urlPath);

		Map<String, Object> infos = GSonTools.getObjectMaps(jsonString);
		Set<String> keys = infos.keySet();
		videos = new ArrayList<NewListInfo>();
		DebugTools.log(className, "currentPage = " + currentPage + "  keys = "
				+ keys);
		for (String key : keys) {
			if (!key.equals("total")) {
				Map<String, Object> map = (Map<String, Object>) infos.get(key);
				videos.add(JsonParserUtils.getNews(map));
			} else {
				// total = Integer.parseInt(infos.get(key))
			}
		}

		return videos;
	}

	/**
	 * 初始化分页信息
	 */
	private void initPage() {
		currentPage = 1;
		int ps = 0;
		if ((ps = total / per) == 0) {
			// 刚好整除时，所得的商就是页数
			allPage = ps;
		} else {
			// 不能整除时，页数为商加一
			allPage = ps + 1;
		}
	}

	// private void changAdv(int len) {
	// currentAdv++;
	// currentAdv = currentAdv % len;
	// viewPager.setCurrentItem(currentAdv);
	// setPiontsBg(currentAdv);
	// }

	/**
	 * 设置小圆点的颜色
	 * 
	 * @param position
	 */
	// private void setPiontsBg(int position) {
	// int len = points.size();
	// for (int i = 0; i < len; i++) {
	// points.get(i).setImageResource(R.drawable.bg_point_unselect);
	// }
	// points.get(position).setImageResource(R.drawable.bg_point_select);
	// }

	@Override
	public void doClick(View v) {

		// Intent intent = new Intent();
		List<VideoListInfo> videos = null;
		// TODO Auto-generated method stub
		switch (v.getId()) {

//		case R.id.v_channel_album_view_image:
//			// DebugTools.log(className, advs.toString());
//			// HttpUtils.browser(advs.get(0).url, context);
//
//			// TODO Auto-generated method stub
//			NewListInfo newInfo = (NewListInfo) newsAdapter.getItem(0);
//			if (newInfo.newsType.equals(NewListInfo.NEWS_TYPE_NEWS)) {
//				Main.news_detailIntent.putExtra("id",
//						Integer.parseInt(newInfo.news_id));
//				ViewLayout.setViewPre(true, "新闻详情",
//						ViewLayout.TAB_TAG_NEWS_DETAIL);
//			} else if (newInfo.newsType.equals("album")) {
//
//				Bundle bundle = new Bundle();
//				bundle.putSerializable(NewListInfo.NEWS_TYPE_ALBUM, newInfo);
//				Main.album_detailIntent.putExtra(NewListInfo.NEWS_TYPE_ALBUM,
//						bundle);
//				ViewLayout.setViewPre(true, "图赏详情",
//						ViewLayout.TAB_TAG_ALBUM_DETAIL);
//			} else if (newInfo.newsType.equals(NewListInfo.NEWS_TYPE_VIDEO)) {
//				HttpUtils.browser(newInfo.v_source_url, context);
//			} else {
//				DebugTools.toast(context, "未知类型的新闻:" + newInfo.newsType);
//			}
//
//			break;
			
		case R.id.list_foot_view:
			onPullDownListener.onMore();
			break ;

		// case R.id.see_more:
		// isRefresh = false ;
		// if (currentPage < allPage ) {
		// footerLoadingMore.setVisibility(View.GONE);
		// footerLoadingProgress.setVisibility(View.VISIBLE);
		// new DownLaodData(context).execute(null);
		// }
		// break;

		default:
			DebugTools.log(className,
					"doClick() 未定义控件单击后的事件...... id = " + v.getId());
			break;

		}
	}

	private class DownLaodData extends
			AsyncTask<String, String, List<NewListInfo>> {
		private Context context;

		// private Progress dialog ;

		public DownLaodData(Context context) {
			super();
			this.context = context;
			// this.dialog = dialog;
		}

		@Override
		protected List<NewListInfo> doInBackground(String... params) {
			// TODO Auto-generated method stub
			List<NewListInfo> news = null;
			try {
				news = getVideos(currentPage, per);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return news;
		}

		@Override
		protected void onPostExecute(List<NewListInfo> result) {
			// TODO Auto-generated method stubif(news!=null&&!news.isEmpty()){
			if (result != null && !result.isEmpty()) {
				if (isRefresh) {
					newsAdapter = new NewsAdapter(result, context);
					videsList.setAdapter(newsAdapter);
					mPullDownView.enableAutoFetchMore(true, 1);
					// 诉它数据加载完毕;
					mPullDownView.notifyDidLoad();
					mPullDownView.notifyDidRefresh();
				} else {
					newsAdapter.adddata(result);
					// 告诉它获取更多完毕
					mPullDownView.notifyDidMore();
				}
				// ListViewUtils.setListViewHeightBaseOnChildren(videsList);
				currentPage++;
				footLoadingProgressBar.setVisibility(View.INVISIBLE);
				footLoadingseeMore.setText("查看更多");
			} else {
				DebugTools.log(className, "网络异常");
				footLoadingProgressBar.setVisibility(View.INVISIBLE);
				footLoadingseeMore.setText("没有了");
			}
			// 诉它数据加载完毕;
//			// 诉它数据加载完毕;
			mPullDownView.notifyDidLoad();
			// 告诉它获取更多完毕
			mPullDownView.notifyDidMore();
//			footLoadingProgressBar.setVisibility(View.INVISIBLE);
//			footLoadingseeMore.setText("查看更多");
			// pullToRefreshView.onHeaderRefreshComplete();
			// pullToRefreshView.onFooterRefreshComplete();
			// footerLoadingMore.setVisibility(View.VISIBLE);
			// footerLoadingProgress.setVisibility(View.GONE);

			super.onPostExecute(result);
			
			//清除软引用中图片缓存缓存
			if(newsAdapter.getCount()>30){
				BitmapUtils.cleanCache();
			}
		}

	}

}
